package com.kfm.coll;

public class MyList {

    private Object[] arr = new Object[10];
    private int count = 0;


    public void add(Object e) {
        // 如果 count >= arr.length 考虑扩容
        if (count >= arr.length) {
            Object[] newArr = new Object[arr.length * 2];
            // 复制原来的数组元素
            // 原数组，开始的位置，新数组，放的位置，长度
            System.arraycopy(arr, 0, newArr, 0, arr.length);
            arr = newArr;
        }
        arr[count] = e;
        count++;
    }

    public Object remove(int index) {
        if (index >= count) {
            return null;
        }
        Object el = arr[index];
        // 如何从数组删除元素 1,2,3,4,5  1,2,4,5  index = 2
        System.arraycopy(arr, 0, arr, 0, index); // 1,2,4,5,5
        System.arraycopy(arr, index + 1, arr, index, count - index - 1); // 4,5
        arr[count - 1] = null;
        count--;
        return el;
    }

    public Object get(int index) {
        return arr[index];
    }

    public String toString() {
        StringBuilder sb = new StringBuilder("[");
        for (int i = 0; i < count; i++) {
            if (i == count - 1) {
                sb.append(arr[i].toString()).append("]");
            } else {
                sb.append(arr[i].toString()).append(",");
            }
        }
        return sb.toString();
    }
}

class MyListText {
    public static void main(String[] args) {
        MyList myList = new MyList();
        myList.add(1);
        myList.add(2);
        myList.add(3);
        System.out.println(myList);
        System.out.println(myList.remove(2));
        System.out.println(myList);
        myList.add(4);
        System.out.println(myList);
    }
}
